package com.sali.asyncollection.controller.asyn_request_merge;

import cn.hutool.json.JSONObject;
import com.sali.asyncollection.model.BannerDTO;
import com.sali.asyncollection.model.BaseRspDTO;
import com.sali.asyncollection.model.LabelDTO;
import com.sali.asyncollection.model.UserInfoDTO;
import com.sali.asyncollection.service.BaseTaskCommand2;
import com.sali.asyncollection.service.ExecuteTaskService;
import com.sali.asyncollection.service.impl.strategy.TaskStrategyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description:
 * @author: sali
 * @date: 2024/8/27 下午8:25.
 * @version: 1.0
 */
@RequestMapping("/admin/v1")
@RestController
@Slf4j
public class TestParallelApi03Controller {

    @Autowired
    private TaskStrategyFactory taskStrategyFactory;


    @GetMapping("/parallel/03")
    public JSONObject parallelController03() {
        String req = "我是req";

        long beginTime = System.currentTimeMillis();
        System.out.println("开始并行查询app首页信息（最终版本），开始时间：" + beginTime);
        List<Callable<BaseRspDTO<Object>>> taskList = new ArrayList<>();
        //用户信息查询任务
        taskList.add(new BaseTaskCommand2("userInfoDTO", req, taskStrategyFactory));
        //banner查询任务
        taskList.add(new BaseTaskCommand2("bannerDTO", req, taskStrategyFactory));
        //标签查询任务
        taskList.add(new BaseTaskCommand2("labelDTO", req, taskStrategyFactory));

        ExecutorService executor = Executors.newFixedThreadPool(10);
        List<BaseRspDTO<Object>> resultList = ExecuteTaskService.executeTask(taskList, 3, executor);

        if (resultList.isEmpty()) {
            log.error("任务执行异常");
            return null;
        }

        UserInfoDTO userInfoDTO = null;
        BannerDTO bannerDTO = null;
        LabelDTO labelDTO = null;

        for (BaseRspDTO<Object> baseRspDTO : resultList) {
            if ("userInfoDTO".equals(baseRspDTO.getKey())) {
                userInfoDTO = (UserInfoDTO) baseRspDTO.getData();
            } else if ("bannerDTO".equals(baseRspDTO.getKey())) {
                bannerDTO = (BannerDTO) baseRspDTO.getData();
            } else if ("labelDTO".equals(baseRspDTO.getKey())) {
                labelDTO = (LabelDTO) baseRspDTO.getData();
            }
        }

        System.out.println("结束并行查询app首页信息（最终版本）,总耗时：" + (System.currentTimeMillis() - beginTime));

        JSONObject result = new JSONObject();
        result.put("userInfoDTO", userInfoDTO);
        result.put("bannerDTO", bannerDTO);
        result.put("labelDTO", labelDTO);
        return result;
    }

}
